﻿using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System;
using UnityEngine.UI;

public class UIButtonProxy : MonoBehaviour 
{
    public enum Trigger
    {
        OnClick,
        OnMouseOver,
        OnMouseOut,
        OnPress,
        OnRelease,
        OnDoubleClick,
    }

    private Button btn;
    public GameObject target;
    public string functionName;
    public Trigger trigger = Trigger.OnClick;
    public bool includeChildren = false;

    protected object customData;
    
    bool mStarted = false;
    bool mHighlighted = false;

    protected virtual void SetData()
    {
        customData = gameObject;
    }

    void Start() {

        btn = CHelper.GetSafeComponent<Button>(gameObject);
        btn.onClick.AddListener(OnBtnClick);

        mStarted = true;

    }

    private void OnDestroy()
    {
        btn.onClick.AddListener(OnBtnClick);
    }

    void OnEnable() { /*if (mStarted && mHighlighted) OnHover(UICamera.IsHighlighted(gameObject));*/ }

    void OnHover(bool isOver)
    {
        if (enabled)
        {
            if (((isOver && trigger == Trigger.OnMouseOver) ||
                (!isOver && trigger == Trigger.OnMouseOut)))
            {
                Send();
            }
            mHighlighted = isOver;
        }
    }

    void OnPress(bool isPressed)
    {
        if (enabled)
        {
            if (((isPressed && trigger == Trigger.OnPress) ||
                (!isPressed && trigger == Trigger.OnRelease)))
            {
                Send();
            }
        }
    }

    void OnClick() 
    {
        if (enabled && trigger == Trigger.OnClick)
        {
            Send();
        }
    }

    void OnDoubleClick() 
    {
        if (enabled && trigger == Trigger.OnDoubleClick)
        {
            Send();
        }
    }

    void Send()
    {
        SetData();

        if (!gameObject.activeInHierarchy || string.IsNullOrEmpty(functionName))
        {
            return;
        }

        if (target == null)
        {
            target = gameObject;
        }

        if (includeChildren)
        {
            Transform[] transforms = target.GetComponentsInChildren<Transform>();

            for (int i = 0, imax = transforms.Length; i < imax; ++i)
            {
                Transform t = transforms[i];
                t.gameObject.SendMessage(functionName, customData, SendMessageOptions.DontRequireReceiver);
            }
        }
        else
        {
            target.SendMessage(functionName, customData, SendMessageOptions.DontRequireReceiver);
        }
    }

    #region UGUI事件监听

    private void OnBtnClick()
    {
        trigger = Trigger.OnClick;
        OnClick();
    }

    #endregion

}
